package com.choosefine.base.attendance.server.listener
import Com.FirstSolver.Splash.FaceId_Item
import Com.FirstSolver.Splash.ISocketServerThreadTask
import Com.FirstSolver.Splash.NetworkStreamPlus
import Com.FirstSolver.Splash.TcpListenerPlus
import org.slf4j.LoggerFactory
import java.io.IOException
import java.net.*
import java.util.*

/**
 * Created by 邱鹏 on 2017/8/28.
 */
class AttendanceListener @Throws(IOException::class, Exception::class)
constructor(serverhost: String, serverport: String) : ISocketServerThreadTask {

    internal var logger = LoggerFactory.getLogger(AttendanceListener::class.java)

    var tcpServer: TcpListenerPlus? = null

    var isPostPhoto = true

    var isServerRunning = false

    init {
        //创建侦听服务器
        tcpServer = TcpListenerPlus(Integer.parseInt(serverport), 0, InetAddress.getByName(serverhost), true)
        //设置通信线程任务委托
        tcpServer!!.ThreadTaskDelegate = this
        //开启侦听服务
        tcpServer!!.StartListenThread(null, 0, 0)
        isServerRunning = true
    }

    @Throws(Exception::class)
    override fun OnServerTaskRequest(stream: NetworkStreamPlus) {
        // 设备特殊通信密码
        // stream.setSecretKey(textFieldSecretKey.getText());  // 注意：密码要和设备通信密码一致

        var SerialNumber: String    // 设备序列号
        while (true) {
            try {
                // 读取数据
                val answer = stream.Read("gbk")

                // 显示读取信息
                logger.info(answer)

                if (answer.startsWith("PostRecord")) {   // 提取序列号并保存
                    SerialNumber = FaceId_Item.GetKeyValue(answer, "sn")

                    // 答复已准备好接收考勤记录
                    if (isPostPhoto) {
                        stream.Write("Return(result=\"success\" postphoto=\"true\")", "gbk")
                    } else {
                        stream.Write("Return(result=\"success\" postphoto=\"false\")", "gbk")
                    }
                } else if (answer.startsWith("Record")) {   // 读取考勤记录

                    // 服务器回应
                    stream.Write("Return(result=\"success\")", "gbk")
                } else if (answer.startsWith("PostEmployee")) {   // 准备上传人员信息

                    // 服务器回应
                    stream.Write("Return(result=\"success\")", "gbk")
                } else if (answer.startsWith("Employee")) {   // 读取人员信息

                    // 服务器回应
                    stream.Write("Return(result=\"success\")", "gbk")
                } else if (answer.startsWith("Quit")) {   // 结束会话
                    break
                }//                else if (answer.startsWith("GetRequest"))
                //                {   // 下发命令
                //                    Platform.runLater(() -> {
                //                        String Command = textAreaCommand.getText();
                //                        if (!Utils.IsNullOrEmpty(Command))
                //                        {
                //                            try
                //                            {
                //                                stream.Write(Command, "gbk");
                //                            }
                //                            catch (Exception ex)
                //                            {
                //
                //                            }
                //
                //                            textAreaCommand.clear();
                //                        }
                //                    });
                //                }
            } catch (ex: Exception) {
                break  // 连接断开
            }

        }
    }

    fun initialize(url: URL, rb: ResourceBundle) {
        // 设置服务器地址
        try {
            val IPList = LinkedList<String>()
            val InterfaceList = NetworkInterface.getNetworkInterfaces()
            while (InterfaceList.hasMoreElements()) {
                val iFace = InterfaceList.nextElement()
                if (iFace.isLoopback || iFace.isVirtual || iFace.isPointToPoint || !iFace.isUp) continue

                val AddrList = iFace.inetAddresses
                while (AddrList.hasMoreElements()) {
                    val address = AddrList.nextElement()
                    if (address is Inet4Address || address is Inet6Address) {
                        IPList.add(address.hostAddress)
                    }
                }
            }

            //            if(!IPList.isEmpty())
            //            {
            //                comboBoxServerIP.setItems(FXCollections.observableList(IPList));
            //                comboBoxServerIP.setValue(IPList.get(0));
            //            }
        } catch (ex: SocketException) {
            // 异常处理
        }

    }
}
